<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\EasyWeChat\Easywechat;
use app\api\model\wanlshop\Paylog;
use app\common\controller\Api;
use app\common\model\FinanceLog;
use app\common\model\MoneyLog;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * WanlShop店铺接口
 */
class Shopdata extends Api
{

    protected $noNeedRight = ['*'];

    protected $shop_info = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\api\model\wanlshop\Shop');

        $shop_info = $this->model->get(['user_id'=>$this->auth->id]);

        if (empty($shop_info)){
            $this->error('当前用户未申请店铺');
        }

        $this->shop_info = $shop_info;
    }

    //订单列表
    public function orderlist()
    {
        //$state = $this->request->request('state');
        $state = input('state','');
        if ($state && $state != 0) {
            $where['state'] = $state;
        } else {
            $where['state'] = ['>',1];
        }
        $where['order_type'] = 1;

        $where['status'] = 'normal';
        $where['shop_id'] = $this->shop_info->id;
        // 列表
        $list = model('app\api\model\wanlshop\Order')
            ->where($where)
            //->where('state','>',1)
            ->field('id,shop_id,user_id,state,createtime,order_no,taketime')
            ->order('updatetime desc')
            ->paginate()
            ->each(function($order, $key){
                $goods = model('app\api\model\wanlshop\OrderGoods')
                    ->where(['order_id'=> $order->id])
                    ->field('id,title,goods_id,image,difference,price,market_price,number,refund_status')
                    ->select();
                $order['goods'] = $goods;
                // 获取支付 1.1.2升级
                $order['pay'] = model('app\api\model\wanlshop\Pay')
                    ->where(['order_id' => $order->id, 'type' => 'goods'])
                    ->field('number, price, order_price, freight_price, discount_price, actual_payment')
                    ->find();
                $user_info = \app\common\model\User::where(['id'=>$order->user_id])->field('id,avatar,nickname,mobile')->find();
                $order['user_info'] = $user_info;
                return $order;
            });

        $this->success('ok', $list);
    }

    //订单详情
    public function orderinfo()
    {
        $id = $this->request->request('id');
        $id ? $id : ($this->error(__('非法请求')));
        $order = model('app\api\model\wanlshop\Order')
            ->where(['id' => $id, 'shop_id' => $this->shop_info->id])
            ->field('id,user_id,shop_id,order_no,isaddress,express_no,express_name,freight_type,state,createtime,paymenttime,delivertime,taketime,dealtime')
            ->find();
        $order ? $order : ($this->error(__('网络异常')));

        // 获取地址
        $order['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        // 获取订单商品
        $order['goods'] = model('app\api\model\wanlshop\OrderGoods')
            ->where(['order_id'=> $id])
            ->field('id,goods_id,title,image,difference,price,market_price,actual_payment,discount_price,freight_price,number,refund_id,refund_status')
            ->select();
        // 获取支付 1.1.2升级
        $order['pay'] = model('app\api\model\wanlshop\Pay')
            ->where(['order_id' => $order->id, 'type' => 'goods'])
            ->field('id, pay_no, number, price, order_price, freight_price, discount_price, actual_payment')
            ->find();
        $user_info = \app\common\model\User::where(['id'=>$order->user_id])->field('id,avatar,nickname')->find();
        $order['user_info'] = $user_info;
        $this->success('ok',$order);
    }

    //核销单信息
    public function verifyInfo()
    {
        //$delivery_code = $this->request->request('delivery_code');
        $delivery_code = input('delivery_code','');
        $delivery_code ? $delivery_code : ($this->error(__('非法请求')));
        $order = model('app\api\model\wanlshop\Order')
            ->where(['delivery_code' => $delivery_code, 'shop_id' => $this->shop_info->id])
            ->field('id,shop_id,user_id,order_no,isaddress,express_no,express_name,freight_type,state,createtime,paymenttime,delivertime,taketime,dealtime')
            ->find();
        $order ? $order : ($this->error(__('网络异常')));
        // 获取订单商品
        $order['goods'] = model('app\api\model\wanlshop\OrderGoods')
            ->where(['order_id'=> $order['id']])
            ->field('id,goods_id,title,image,difference,price,market_price,actual_payment,discount_price,freight_price,number,refund_id,refund_status')
            ->select();
        // 获取支付 1.1.2升级
        $order['pay'] = model('app\api\model\wanlshop\Pay')
            ->where(['order_id' => $order->id, 'type' => 'goods'])
            ->field('id, pay_no, number, price, order_price, freight_price, discount_price, actual_payment')
            ->find();

        $user_info = \app\common\model\User::where(['id'=>$order->user_id])->field('id,avatar,nickname,mobile')->find();
        $order['user_info'] = $user_info;
        $this->success('ok',$order);
    }

    //核销
    public function verify()
    {
        $delivery_code = input('delivery_code','');
        $delivery_code ? $delivery_code : ($this->error(__('非法请求')));
        $order = model('app\api\model\wanlshop\Order')
            ->where(['delivery_code' => $delivery_code, 'shop_id' => $this->shop_info->id])
            ->field('id,shop_id,user_id,order_no,isaddress,express_no,express_name,freight_type,state,createtime,paymenttime,delivertime,taketime,dealtime')
            ->find();
        $order ? $order : ($this->error(__('网络异常')));

        if ($order['state']!=3){
            $this->error(__('待提货状态才可核销'));
        }

        Db::startTrans();
        try {
            // 获取支付 1.1.2升级
           /* $pay = model('app\api\model\wanlshop\Pay')->get(['order_id' => $order['id'], 'type' => 'goods']);
            // 平台转款给商家
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$pay['price'], $order['shop']['user_id'], '卖家核销', 'pay', $order['order_no']);
            // 查询是否有退款
            $refund = model('app\api\model\wanlshop\Refund')
                ->where(['order_id' => $order['id'], 'state' => 4, 'order_type' => 'goods'])
                ->select();
            // 退款存在
            if($refund){
                foreach($refund as $value){
                    controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$value['price'], $order['shop']['user_id'], '该订单存在的退款', 'pay', $order['order_no']);
                }
            }*/
            // 更新退款
            $order->save(['state' => 4,'taketime' => time()],['id' => $order['id']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('ok', $order ? true : false);
    }

    //统计
    public function data()
    {
        //手续费(扫码交易)--扫码没有手续费
        $user = \app\admin\model\User::get($this->auth->id);
        $time_type = input('time_type',0);
        $end_date = time();
        switch ($time_type) {
            case 1:
                //今天
                $start_date = strtotime(date('Y-m-d 00:00',time()));
                break;
            case 2:
                //昨天
                $start_date = strtotime('-1 day');
                break;
            case 3:
                //近七天
                $start_date = strtotime('-7 day');
                break;
            case 4:
                //近三十天
                $start_date = strtotime('-30 day');
                break;
            case 5:
                //自定义筛选
                $start_date = strtotime(input('start_date',''));
                $end_date = strtotime(input('end_date',''));
                break;
        }
        //dump($start_date);
        //dump($end_date);die;
        //补贴金额
        $subsidy_where = ['user_id'=>$this->auth->id,'type'=>'paylog'];
        if($time_type>0){
            $subsidy_where['createtime'] = ['between', [$start_date, $end_date]];
        }

        $subsidy = MoneyLog::where($subsidy_where)->sum('money');
        //优惠总金额(让利给客户的总金额)-消费金
        $finance_where = ['shop_id'=>$this->shop_info->id,'type'=>'paylog'];
        if($time_type>0){
            $finance_where['createtime'] = ['between', [$start_date, $end_date]];
        }

        $finance = FinanceLog::where($finance_where)->sum('finance');

        //线下交易总金额(扫码交易的总金额)，
        $pay_where = ['shop_id'=>$this->shop_info->id,'type'=>0,'pay_status'=>1];
        if($time_type>0){
            $pay_where['createtime'] = ['between', [$start_date, $end_date]];
        }
        $pay_price = Paylog::where($pay_where)->sum('price');
        $data = [
            'subsidy'=>$subsidy,//补贴金额
            'money'=>$user->money,//佣金账户(核销商品获得的佣金或者消费金支付获得的金额)，
            'finance'=>$finance,//补贴给用户的消费金
            'pay_price'=>$pay_price,//线下交易总金额

        ];

        $this->success('',$data);
    }

}